﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameplayManager : Singleton<GameplayManager> 
{
    [Range(2, 10)]
    public int m_LineSegmentsToCalculate = 5;
    [Range(0f, 1f)]
    public float m_MinimumLineDistance = 0.55f;
    
    public float m_ThrowSpeed = 4250f;
    public float m_StraightLineThreshold = 0.05f;
    public float m_MinStraightLineDirection = 0.01f;
    public float m_DirectionMaxLimit = 0.1f;


    private List<Vector3> m_LineDirections;
    public List<Vector3> LineDirections
    {
        get { return m_LineDirections; }
    }

    private List<ResettableObject> m_ResettableObjects = new List<ResettableObject>();

    private void Start()
    {
        RefManager.Instance.m_MouseLineRenderer.m_OnLineStart += OnMouseLineStart;
        RefManager.Instance.m_MouseLineRenderer.m_OnLineEnd += OnMouseLineEnd;
        m_LineDirections = new List<Vector3>();
    }

    private void Update()
    {
        // RIGHT CLICK
        if(Input.GetMouseButtonDown(1))
        {
            ResetAllObjects();
        }
    }
    
    private void OnMouseLineStart()
    {
        m_LineDirections.Clear();
    }

    private void OnMouseLineEnd()
    {
        List<Vector3> pointsPos = RefManager.Instance.m_MouseLineRenderer.PointsPosition;
        int numberOfPoints = pointsPos.Count;

        if(numberOfPoints < 7 || numberOfPoints > 30 || pointsPos[3].y - pointsPos[0].y <= 0)
        {
            return;
        }

        int deltaPoints = Mathf.CeilToInt(numberOfPoints/(m_LineSegmentsToCalculate - 1f));

        for(int i = 0; i < numberOfPoints - 1; i += deltaPoints)
        {
            m_LineDirections.Add(pointsPos[i]);
        }
        
        m_LineDirections.Add(pointsPos[numberOfPoints - 1]);

        //Debug.Log(m_LineDirections[m_LineDirections.Count - 1].y - m_LineDirections[0].y);

        if(m_LineDirections[m_LineDirections.Count - 1].y - m_LineDirections[0].y >= m_MinimumLineDistance)
        {
            RefManager.Instance.m_CurrentBowlingBall.ThrowBall();
        }
    }

    private void ResetAllObjects()
    {
        for(int i = 0; i < m_ResettableObjects.Count; i++)
        {
            m_ResettableObjects[i].aTransform.position = m_ResettableObjects[i].InitialInfo.m_InitialPosition;
            m_ResettableObjects[i].aTransform.rotation = m_ResettableObjects[i].InitialInfo.m_InitialRotation;
            if(m_ResettableObjects[i].aRigidbody != null)
            {
                m_ResettableObjects[i].aRigidbody.velocity = Vector3.zero;
                m_ResettableObjects[i].aRigidbody.angularVelocity = Vector3.zero;
            }
        }
    }
    
    public void RegisterResetObject(ResettableObject i_ResettableObject)
    {
        m_ResettableObjects.Add(i_ResettableObject);
    }
}
